import { ref, watch } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useDialogStore } from '@/store/dialog'
import { unRefArray } from '@/utils/transform'
import { FEED_PERMISION, MEDIA_TYPE } from '@/constant'
import API from '@/http'

const accountStore = useAccountStore()
const { userData } = storeToRefs(accountStore)
const dialogStore = useDialogStore()
const { loadingMask } = storeToRefs(dialogStore)

export const useFanSendSet = defineStore('fanSendSet', () => {
  const selectedArray = ref([])
  const updateSelectedArray = ref({})
  const selectedLength = ref(0)
  const selectedItemsArray = ref([])

  // 粉絲訊息設定，創作者 Switch 按鈕
  const isSent = ref(false)
  if (userData.value.push_button === true) {
    isSent.value = true
  } else {
    isSent.value = false
  }
  function fanSendSetOpen() {
    isSent.value = true
  }
  function fanSendSetClose() {
    isSent.value = false
  }

  // 進入頁面時，啟動觸發動作
  const isTrigger = ref(false)
  function fanSendSetTurnOn() {
    isTrigger.value = true
  }
  function fanSendSetTurnOff() {
    isTrigger.value = false
  }

  // 進入頁面時都要打開這api，為了可以要到資料
  const initList = ref(null)
  const pushListCntLength = ref(0)
  const pushListId = ref(null)
  async function refreshPushList() {
    try {
      const response = await API.Creator.pushlist({ data: {} })
      if (response) {
        console.log(response, '一開始拿到的後端資料')
        initList.value = response
        pushListCntLength.value = response.content.length
        pushListId.value = response.id

        // 要轉成「粉絲訊息設定」的資料格式，讓他在頁面可以顯示已發布過的媒體
        if (pushListCntLength.value > 0) {
          const newArray = []
          initList.value.content.forEach((item) => {
            const newObj = {
              ...item,
              content: {
                mv_img_path: item.mv_img_path,
                mv_id: item.mv_id,
                content: item.content,
                mv_time: item.mv_time,
                mv_money: item.mv_money,
                mv_type: item.mv_type,
              },
            }
            newArray.push(newObj)
          })
          console.log(newArray, '初始資料')
          selectedArray.value = newArray
          selectedLength.value = newArray.length
        } else {
          console.log('你的content是空的唷！')
        }
      } else {
        console.log('你的response是空的唷！')
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 拿取該創作者全部的媒體貼文資料，和發布過的媒體做對比媒體 id ，為了讓「選擇媒體頁」可以打勾勾
  async function getAllMediaData() {
    const PAGE_LIMIT = 10

    if (pushListCntLength.value) {
      loadingMask.value = true

      // 定義一個函數，用於從後端獲取指定類型的數據
      const fetchData = async (type, visible) => {
        let page = 1
        let data = []
        let hasMoreData = true

        while (hasMoreData) {
          try {
            const response = await API.Publish.list({
              data: { type, visible, page, limit: PAGE_LIMIT },
            })

            if (response && response.length > 0) {
              // 合併當前頁面的數據到總數據中
              // 當第二次獲取 response 時，...data 為第一次獲取的數據，...response 是第二次新獲取的數據，第三次第四次以此類推
              data = [...data, ...response]
              page++ // 增加頁數

              // 如果返回的數據少於每頁的數據量，表示沒有更多數據了
              if (response.length < PAGE_LIMIT) {
                hasMoreData = false
              }
            } else {
              hasMoreData = false // 如果返回空數組，表示沒有更多數據了
            }
          } catch (error) {
            console.log(error)
            hasMoreData = false
          }
        }
        return data
      }

      // 用解構賦值，使用 Promise.all 同時發送多個請求
      const [subVideosArr, subPhotosArr, shopVideosArr, shopPhotosArr] = await Promise.all([
        fetchData(MEDIA_TYPE.VIDEO, FEED_PERMISION.SUB),
        fetchData(MEDIA_TYPE.PHOTO, FEED_PERMISION.SUB),
        fetchData(MEDIA_TYPE.VIDEO, FEED_PERMISION.SHOP),
        fetchData(MEDIA_TYPE.PHOTO, FEED_PERMISION.SHOP),
      ])

      const mergedMediaArr = [...subVideosArr, ...subPhotosArr, ...shopVideosArr, ...shopPhotosArr]

      // 使用 filter 過濾出和 mv_id 相同數據
      const filteredArray = mergedMediaArr.filter((item) =>
        selectedArray.value.some((selectedItem) => selectedItem.mv_id === item.id),
      )

      // 遍歷 filteredArray，將對應的 selectedArray 中的 content 複製到 filteredArray 中
      const resultArray = filteredArray.map((filteredItem) => {
        const selectedItem = selectedArray.value.find((selectedItem) => selectedItem.content.mv_id === filteredItem.id)

        if (selectedItem) {
          // 如果找到對應的 selectedArray 物件，則複製 content 到 filteredArray
          return {
            ...filteredItem,
            content: {
              content: selectedItem.content.content,
              mv_id: selectedItem.content.mv_id,
              mv_img_path: selectedItem.content.mv_img_path,
              mv_time: selectedItem.content.mv_time,
              mv_money: selectedItem.content.mv_money,
              mv_type: selectedItem.content.mv_type,
            },
          }
        }

        // 如果找不到對應的 selectedArray 物件，直接返回 filteredArray 中的物件
        return filteredItem
      })

      selectedItemsArray.value = resultArray
      selectedArray.value = resultArray
      loadingMask.value = false
    }
  }

  // 選擇媒體
  const onSelectedItemUpdated = (items) => {
    if (pushListCntLength.value) {
      console.log('如果pushList 有id 會跑過來')
      const newArray = []
      items.forEach((item) => {
        const newObj = {
          ...item,
          content: {
            mv_img_path: item.img_path,
            mv_id: item.id,
            content: '',
            mv_time: item.video_time,
            mv_money: item.money,
            mv_type: item.type,
          },
        }
        newArray.push(newObj)
      })
      updateSelectedArray.value = newArray
      console.log(updateSelectedArray, '選擇貼文時，看得到陣列')
      selectedArray.value = updateSelectedArray.value
    } else {
      console.log('如果pushList 沒有id 會跑過來')
      const newArray = []
      unRefArray(items).forEach((item) => {
        const newObj = {
          ...item,
          content: {
            mv_img_path: item.img_path,
            mv_id: item.id,
            content: '',
            mv_time: item.video_time,
            mv_money: item.money,
            mv_type: item.type,
          },
        }
        newArray.push(newObj)
      })
      updateSelectedArray.value = newArray
      selectedArray.value = updateSelectedArray.value
      console.log(updateSelectedArray, '選擇貼文時，看得到陣列和新增的content')
    }
  }

  // 刪除媒體訊息
  const removeSelectItem = (item) => {
    const indexToRemove = selectedArray.value.findIndex((i) => i === item)
    if (indexToRemove !== -1) {
      selectedArray.value.splice(indexToRemove, 1)
      console.log('在store中看 selectedArray', selectedArray.value)
      selectedLength.value = selectedArray.value.length
    }
  }

  // 監聽 selectedArray 有沒有變動
  watch(selectedArray, (newSelectedArray) => {
    selectedItemsArray.value = newSelectedArray
  })

  return {
    isTrigger,
    isSent,
    initList,
    pushListId,
    selectedArray,
    updateSelectedArray,
    selectedLength,
    selectedItemsArray,
    refreshPushList,
    removeSelectItem,
    onSelectedItemUpdated,
    fanSendSetTurnOn,
    fanSendSetTurnOff,
    fanSendSetOpen,
    fanSendSetClose,
    getAllMediaData,
  }
})
